% [1] F. Plestan, Y. Shtessel, V. Brégeault, and A. Poznyak, 
% “New methodologies for adaptive sliding mode control,” 
% Int. J. Control, vol. 83, no. 9, pp. 1907–1919, Sep. 2010, doi: 10.1080/00207179.2010.501385.
% in section 3.2 Second adaptive sliding mode control law
% TODO: the estimation panick
clc
clear
%% initialize parameters
params=struct();
tfinal=200;
params.t=linspace(0,tfinal,1000);
params.delta=5*sin(0.05*params.t);
params.kbar=1000;
params.epsilon=0.1;
params.mu=2;
params.s=1.5;
initial=[2;1];

%% run the simulation
opt=odeset("AbsTol",1e-4,"RelTol",1e-4,"OutputFcn","odeplot");
[t,x]=ode45(@(t,x)rhs(t,x,params),linspace(0,tfinal,500),initial,opt);
save adaptive_sign2.mat
%% plot results
figure;
nexttile;hold on;
plot(t,x(:,1));
nexttile;hold on;
plot(t,x(:,2));
plot(params.t,params.delta)
legend(["k","\delta"])
ylim([0,3])
exportgraphics(gcf,"adaptive_sign2.png")

%%
function [dxdt]=rhs(t,states,p)
    x=states(1);
    k=states(2);
    if k<p.mu
        dotk=p.mu;
    else
        dotk=p.kbar*abs(x)*sign(abs(x)-0.1);
    end
    %delta=interp1(p.t,p.delta,t);
    u=-k*sign(x);
    dxdt=[u+5*sin(0.05*t);dotk];
end